﻿Imports System.IO
Imports System.Reflection
Imports XCLI_API

Module XCLI_Console
    Public env() As String

    'initializes any variables
    Sub init()
        'This should be fairly self explainatory.
        ReDim env(1)
        env(0) = "C:\"
        env(1) = Environment.CurrentDirectory & "\Plugins"


        'initialize any filesystem variables
        init_filesystem()
    End Sub

    Sub init_filesystem()
        If Not Directory.Exists(env(1)) Then
            Directory.CreateDirectory(env(1))
        End If
        If Not File.Exists(env(1) & "\manifest.xml") Then
            Manifest_Control.create()
        End If
    End Sub


    Sub Main()
        'call initialize sub
        init()

        Do
            Console.Write("[" & Environment.UserName & "@" & Environment.MachineName & "]: " & env(0) & "> ")
            Dim command As String = Console.ReadLine()
            Dim commandArr() As String = command.Split(" ")

            'If commands is to exit, then quit the application
            If commandArr(0).ToLower = "quit" Or commandArr(0).ToLower = "exit" Then
                End
            End If

            'If not, then find the DLL
            Dim appDir As String = env(1)
            Dim DLL As String = Manifest_Control.Read_File(commandArr(0))
            If Not DLL = "0" Then
                If File.Exists(env(1) & "\" & DLL) Then

                    Dim asm As Assembly = Assembly.LoadFrom(appDir & "\" & DLL)
                    Dim myType As System.Type = asm.GetType(asm.GetName.Name + ".Plugin")
                    Dim implementsXCLIPlugin As Boolean = GetType(XCLIPlugin).IsAssignableFrom(myType)
                    If implementsXCLIPlugin Then
                        'Console.WriteLine(asm.GetName.Name + " is a valid plugin!")
                        Dim plugin As XCLIPlugin = CType(Activator.CreateInstance(myType), XCLIPlugin)
                        'Console.WriteLine(plugin.CommonName & plugin.Description)
                        plugin.CONSTRUCT(command, env)
                    End If
                Else
                    Console.WriteLine("Error: """ & DLL & """ not found.")
                End If
            Else
                Console.WriteLine("""" & commandArr(0) & """ is not a valid command.")
            End If


        Loop
    End Sub


End Module
